package com.vcens.dingnotice.task.init;

import com.dingtalk.chatbot.DingtalkChatbotClient;
import com.dingtalk.chatbot.SendResult;
import com.dingtalk.chatbot.message.Message;
import com.vcens.dingnotice.service.impl.TaskerServiceImpl;
import com.vcens.dingnotice.message.dingtalk.DingMessageFactory;
import com.vcens.dingnotice.message.MessageProducer;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.io.IOException;
import java.io.Serializable;

/**
 * @Author VeChar
 * @Desc    所有添加的钉钉机器人通知类消息都会走这个执行类
 * @CreateTime 2018/9/29 11:54 PM
 **/
@Slf4j
public class DingMessageTask extends QuartzJobBean implements Serializable {
    @Value("${app.dingrobot-token}")
    private String DingTalkRobotToken;

    @Autowired
    private TaskerServiceImpl taskerService;

    private static final long serialVersionUID = 1345965759896560695L;

    private DingtalkChatbotClient client = new DingtalkChatbotClient();

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        log.info(this.getClass().getName() + " has been started...");
        JobDataMap jobDataMap = context.getMergedJobDataMap();
        Integer id = (Integer) jobDataMap.get("JOBID");
        DingMessageFactory dingMessageFactory =
                new MessageProducer().getMessageType(id);
        Message message = dingMessageFactory.buildMessage(id);
        try {
            SendResult result = client.send(DingTalkRobotToken, message);
            if (result.isSuccess()) {
                log.info("通知发送成功");
            } else {
                log.info("通知发送失败");
            }
        } catch (IOException e) {
            log.error("通知发送异常:" + e.fillInStackTrace());
        }
    }
}
